﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CamShared;
using System.Threading;
using System.Diagnostics;
using DavuxLib;

namespace CamServer
{
    public partial class MainForm : DavuxLib.Controls.AeroForm
    {

        MenuItem CameraList = new MenuItem();
        ListViewGroup DefaultGroup = null;

        public static MainForm CurrentInstance = null;

        public MainForm()
        {
            CurrentInstance = this;
            InitializeComponent();

            ContextMenu c = new ContextMenu();

            MenuItem menu = new MenuItem();
            menu.Text = "About CamServer";
            menu.Click += new EventHandler(About_Click);
            c.MenuItems.Add(menu);

            CameraList.Text = "";
            c.MenuItems.Add(CameraList);

            menu = new MenuItem();
            menu.Text = "Settings (Advanced)";
            menu.Click += new EventHandler(Settings_Click);
            c.MenuItems.Add(menu);

            menu = new MenuItem();
            menu.Text = "Control Panel";
            menu.DefaultItem = true;
            menu.Click += new EventHandler(CP_Click);
            c.MenuItems.Add(menu);

            menu = new MenuItem();
            menu.Text = "Start when Windows Starts";
            menu.Checked = DavuxLib.Startup.WillRunAtStartup("CamServer");
            menu.Click += new EventHandler(Startup_Click);
            c.MenuItems.Add(menu);

            menu = new MenuItem();
            menu.Text = "-";
            c.MenuItems.Add(menu);

            menu = new MenuItem();
            menu.Text = "Exit";
            menu.Click += new EventHandler(Exit_Click);
            c.MenuItems.Add(menu);

            NI.ContextMenu = c;
            NI.Icon = this.Icon;
            NI.Visible = true;
            NI.MouseClick += new MouseEventHandler(NI_MouseClick);


            _GlassArea.Bottom = ClientRectangle.Height - lsv.Location.Y - lsv.Height - 2;

            if (Settings.Get("Settings|Show Control Panel On Startup", true))
            {
                chkOpenDefault.Checked = true;
                Show();
                Activate();
            }

            if (!Settings.Get("#Settings|WMV9VCM_INSTALLED", false))
            {
                new Thread(InstallWMVCodec).Start();
            }
        }

        void InstallWMVCodec()
        {
            try
            {
                System.Diagnostics.Process.Start("wmv9vcmsetup.exe", "/Q");
                Settings.Set("#Settings|WMV9VCM_INSTALLED", true);
                Trace.WriteLine("**** Installed WMV9 Codecs!");
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error installing WMVVCMSetup: " + ex);
            }
        }

        void NI_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Opacity = 1;
                Show();
                Activate();
            }
        }

        void NI_DoubleClick(object sender, EventArgs e)
        {
            Opacity = 1;
            Show();
            Activate();
        }

        void NI_Click(object sender, EventArgs e)
        {
            Opacity = 1;
            Show();
            Activate();
        }

        void Exit_Click(object sender, EventArgs e)
        {
            NI.Visible = false;
            Viewer.CloseAll();
            CamHost.Dispose();
            Environment.Exit(DavuxLib.RoboRestarter.GracefulExitCode);
        }

        void About_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.ShowDialog();
        }

        void Startup_Click(object sender, EventArgs e)
        {
            MenuItem mi = (MenuItem)sender;
            mi.Checked = !mi.Checked;
            DavuxLib.Startup.RunAtStartup("CamServer", mi.Checked);
        }

        void Settings_Click(object sender, EventArgs e)
        {
            SettingsViewer sv = new SettingsViewer();
            sv.Show();
        }

        void CP_Click(object sender, EventArgs e)
        {
            Opacity = 1;
            Show();
        }

        public void OnCameraAdded(ICamera cam)
        {
            MenuItem camItem = new MenuItem();
            camItem.Text = cam.Name;
            camItem.Tag = cam;
            camItem.Click += new EventHandler(camItem_Click);
            CameraList.Text = "View Camera";
            CameraList.MenuItems.Add(camItem);

            if (Settings.Get("#" + cam.Name + "|WasOpen", false))
            {
                camItem_Click(camItem, null);
            }
            this.Invoke((MethodInvoker)delegate()
            {
                LoadView();
            });


        }

        void camItem_Click(object sender, EventArgs e)
        {
            ICamera cam = (ICamera)((MenuItem)sender).Tag;
            Thread t = new Thread(new ParameterizedThreadStart(OpenWindow));
            t.Start(cam);
        }

        void OpenWindow(object cam)
        {
            Viewer v = new Viewer((ICamera)cam);
            v.Show();
            Application.Run();
        }


        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            glowLabel1.Invalidate();
        }



        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            Invalidate();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            Hide();
            Opacity = 0;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            ColumnHeader c = new ColumnHeader();
            c.Text = "Camera";
            lsv.Columns.Add(c);
            c = new ColumnHeader();
            c.Text = "Device Type";
            lsv.Columns.Add(c);

            DefaultGroup = new ListViewGroup();
            DefaultGroup.Header = "My Cameras (" + Settings.Get("UPnP Unity|HostName", System.Environment.MachineName)  + ")";
            lsv.Groups.Add(DefaultGroup);

            LoadView();
        }

        private void LoadView()
        {
            lsv.Items.Clear();
            foreach (ICamera cam in CamHost.Cameras.ToArray())
            {
                string host = "";
                string name = "";

                if (cam.Name.IndexOf(":") > -1)
                {
                    host = cam.Name.Substring(0, cam.Name.IndexOf(":")).Trim();
                    name = cam.Name.Substring(host.Length + 1).Trim();
                }
                else
                {
                    name = cam.Name;
                }

                ListViewItem lvi = new ListViewItem();
                lvi.Text = name;
                lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, cam.Class));
                lvi.Group = DefaultGroup;
                lvi.Tag = cam;

                if (host != "")
                {
                    foreach (ListViewGroup g in lsv.Groups)
                    {
                        if (g.Header == "Cameras on " + host)
                        {
                            lvi.Group = g;
                            break;
                        }
                    }

                    if (lvi.Group == DefaultGroup)
                    {
                        ListViewGroup ng = new ListViewGroup();
                        ng.Header = "Cameras on " + host;
                        lsv.Groups.Add(ng);
                        lvi.Group = ng;
                    }
                }

                lsv.Items.Add(lvi);
            }

            foreach (ColumnHeader col in lsv.Columns)
            {
                col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        }

        private void lsv_MouseClick(object sender, MouseEventArgs e)
        {

            if (lsv.SelectedItems.Count > 0 && e.Button == MouseButtons.Right)
            {
                ICamera cam = (ICamera)lsv.SelectedItems[0].Tag;
                mnuProperties.Tag = cam;
                mnuRecording.Checked = Settings.Get(cam.Name + "|Recording", false);
                mnuShared.Checked = Settings.Get(cam.Name + "|Unity Sharing", false);
                lsv_Menu.Show(lsv, e.Location);
            }
        }

        private void chkOpenDefault_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Set("Settings|Show Control Panel On Startup", chkOpenDefault.Checked);
        }

        private void mnuRecording_Click(object sender, EventArgs e)
        {
            mnuRecording.Checked = !mnuRecording.Checked;
            ICamera cam = (ICamera)lsv.SelectedItems[0].Tag;
            Settings.Set(cam.Name + "|Recording", mnuRecording.Checked);
        }

        private void mnuShared_Click(object sender, EventArgs e)
        {
            mnuShared.Checked = !mnuShared.Checked;
            ICamera cam = (ICamera)lsv.SelectedItems[0].Tag;
            Settings.Set(cam.Name + "|Unity Sharing", mnuShared.Checked);
        }

        private void mnuView_Click(object sender, EventArgs e)
        {
            ICamera cam = (ICamera)lsv.SelectedItems[0].Tag;
            Viewer.ShowCamera(cam);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Preferences p = new Preferences();
            p.StartPosition = FormStartPosition.CenterParent;
            p.ShowDialog(this);
        }

        private void lsv_DoubleClick(object sender, EventArgs e)
        {
            if (lsv.SelectedItems.Count > 0)
            {
                ICamera cam = (ICamera)lsv.SelectedItems[0].Tag;
                Viewer.ShowCamera(cam);
            }
        }

        private void mnuProperties_Click(object sender, EventArgs e)
        {
            CameraProperties cp = new CameraProperties((ICamera)((MenuItem)sender).Tag);
            cp.StartPosition = FormStartPosition.CenterParent;
            cp.ShowDialog(this);
        }
    }
}
